package one.stand.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectResult;
import one.stand.entity.ImageVEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * oss文件上传
 * @author Administrator
 */
@Component
public class OssUtil {

    /**
     * log日志
     */
    private static Logger logger = LoggerFactory.getLogger(OssUtil.class);
    /**
     * 阿里云API的密钥Access Key ID
     */
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    /**
     * 阿里云API的密钥Access Key Secret
     */
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    /**
     * 阿里云API的bucket名称
     */
    @Value("${oss.bucketName}")
    private String bucketName;
    /**
     * 阿里云API的内或外网域名
     */
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.url}")
    private String url;


    private String[] imgPrefix = new String[]{"jpg", "png", "jpeg"};
    private String[] recording = new String[]{"mp3"};
    private String[] av = new String[]{"avi","mpg","mlv","mpe","mpeg","dat","mp4"};
    /**
     * 上传文件至OSS
     * @param  file MultipartFile类型
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObjectOSS(MultipartFile file,ImageVEntity isImage) {
        OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        isBucket(client);
        try {
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            PutObjectResult result = client.putObject(bucketName, isImage.getUrl(), file.getInputStream());
            if (result != null) {
                return isImage.getUrl();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("上传异常",e);
        } finally {
            client.shutdown();
        }
        return null;
    }

    /**
     * 上传图片
     * @param bufferedImage
     * @param isImage
     * @return
     */
    public String upload(BufferedImage bufferedImage, ImageVEntity isImage){
        OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        isBucket(client);
        try {
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //保存新图片
            ImageIO.write(bufferedImage, isImage.getPrefix(), os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            PutObjectResult result = client.putObject(bucketName, isImage.getUrl(), is);
            if (result != null) {
                return isImage.getUrl();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("上传异常",e);
        } finally {
            client.shutdown();
        }
        return null;
    }
    /**
     * 上传文件至OSS
     * @param  file MultipartFile类型
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObjectOSS(BufferedInputStream file) {
        OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        isBucket(client);
        try {
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            String prefix = "png";
            String fileUrl = getType(prefix);
            PutObjectResult result = client.putObject(bucketName, fileUrl, file);
            if (result != null) {
                return fileUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("上传异常",e);
        } finally {
            client.shutdown();
        }
        return null;
    }

    /**
     * 判断容器是否存在,不存在就创建
     * @param client
     */
    public void  isBucket(OSSClient  client){
        // 判断容器是否存在,不存在就创建
        if (!client.doesBucketExist(bucketName)) {
            client.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            client.createBucket(createBucketRequest);
        }
    }



    /**
     * 上传文件至OSS
     * @param  file File
     * @param  inputStream 文件流
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObjectOSS(File file, InputStream inputStream) {
        OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        isBucket(client);
        try {
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            String fileName = file.getName();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String fileUrl = getType(prefix);
            PutObjectResult result = client.putObject(bucketName, fileUrl, inputStream);
            if (result != null) {
                return fileUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 上传文件至OSS
     * @param  inputStream 文件流
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObjectOSS(InputStream inputStream,String prefix) {
        OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
        isBucket(client);
        try {
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            String fileUrl = getType(prefix);
            PutObjectResult result = client.putObject(bucketName, fileUrl, inputStream);
            if (result != null) {
                return fileUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 更加日期创建文件夹
     *
     * @param prefix 后缀
     * @return
     */
    private String getType(String prefix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        StringBuffer buffer = new StringBuffer("one-stand/");
        for (String i : imgPrefix) {
            if (i.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("photo/").append(date).append("/").append(System.currentTimeMillis()).append(".").append(prefix);
                return buffer.toString();
            }
        }
        for (String r : recording) {
            if (r.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("recording/").append(date).append("/").append(System.currentTimeMillis()).append(".").append(prefix);
                return buffer.toString();
            }
        }
        for (String r : av) {
            if (r.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("video/").append(date).append("/").append(System.currentTimeMillis()).append(".").append(prefix);
                return buffer.toString();
            }
        }
        return buffer.append("other/").append(date).append("/").append(System.currentTimeMillis()).append(".").append(prefix).toString();
    }



    public ImageVEntity getType(MultipartFile file, String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String fileName = file.getOriginalFilename();
        StringBuffer buffer = new StringBuffer("one-stand/");
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String date = sdf.format(new Date());
        for (String i : imgPrefix) {
            if (i.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("photo/").append(date).append("/").append(name).append(".").append(prefix);
                ImageVEntity isImage=ImageVEntity.builder().isImage(true).prefix(prefix).url(buffer.toString()).build();
                return isImage;
            }
        }
        for (String r : recording) {
            if (r.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("recording/").append(date).append("/").append(name).append(".").append(prefix);
                ImageVEntity isImage=ImageVEntity.builder().isImage(false).prefix(prefix).url(buffer.toString()).build();
                return isImage;
            }
        }
        for (String r : av) {
            if (r.toLowerCase().equals(prefix.toLowerCase())) {
                buffer.append("video/").append(date).append("/").append(name).append(".").append(prefix);
                ImageVEntity isImage=ImageVEntity.builder().isImage(false).prefix(prefix).url(buffer.toString()).build();
                return isImage;
            }
        }
        buffer.append("other/").append(date).append("/").append(name).append(".").append(prefix);
        return ImageVEntity.builder().isImage(false).prefix(prefix).url(buffer.toString()).build();
    }

    public String getOssUrl() {
        return url;
    }

}
